﻿import os
import nls
import time
import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

ACCESS_KEY_ID = 'LTAI5tLGeog45A1XHH7DyqQs'
ACCESS_KEY_SECRET = 'qoZcsfA7SP15IDRPpZQ1TCdFqO6IkW'
APP_KEY = '3DW2sNcoMlK3L4Cx'

print("="*70)
print("测试 NlsSpeechSynthesizer")
print("="*70)

# 获取 Token
client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, 'cn-shanghai')
request = CommonRequest()
request.set_method('POST')
request.set_domain('nls-meta.cn-shanghai.aliyuncs.com')
request.set_version('2019-02-28')
request.set_action_name('CreateToken')
response = client.do_action_with_exception(request)
jss = json.loads(response)
token = jss['Token']['Id']
print(f"Token: {token[:20]}...")

# 测试合成
audio_data = []
completed = False

def on_data(data, *args):
    audio_data.append(data)
    print(f"接收: {len(data)} bytes")

def on_completed(msg, *args):
    global completed
    completed = True
    print("完成!")

def on_error(msg, *args):
    print(f"错误: {msg}")

def on_close(*args):
    pass

synthesizer = nls.NlsSpeechSynthesizer(
    url='wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1',
    token=token,
    appkey=APP_KEY,
    on_data=on_data,
    on_completed=on_completed,
    on_error=on_error,
    on_close=on_close
)

synthesizer.start(
    text="这是测试",
    voice="longyuan",
    aformat='wav',
    sample_rate=16000
)

# 等待
waited = 0
while not completed and waited < 10:
    time.sleep(0.1)
    waited += 0.1

print(f"结果: {len(audio_data)} 块, {sum(len(d) for d in audio_data)} bytes")

if audio_data:
    with open('test_output.wav', 'wb') as f:
        for chunk in audio_data:
            f.write(chunk)
    print("成功! 文件: test_output.wav")
else:
    print("失败! 没有数据")
